/**
 * Created by a1 on 2017/10/16.
 */
"use strict";
var fs = require('fs');
var formidable = require('formidable');
var common = require('../models/common.js');
var BookModel = require('../models/Book.js');//书本Schema
var AuthorModel = require('../models/Author.js');//作者Schema
var BookreviewModel = require('../models/Bookreview.js');//书评Schema
var UserinfoModel = require('../models/Userinfo.js');//用户Schema
var UsernameModel = require('../models/Username.js');//用户Schema
var AriafansnumModel = require('../models/Ariafansnum.js');//打赏Schema
var AriafansModel = require('../models/Ariafans.js');//总打赏Schema
var BookshelfModel=require('../models/Bookshelf.js');

//书本详情
exports.bookKey=function(req,res){
    let session=false;
    if(req.session.username){
        session=true;
    }
    if(!isNaN(req.params.key)){
        res.render('book',{
            page:'book',
            bid:req.params.key,
            session:session,
            uid:req.session.username?req.session.uid:""
        });
    }else {
        res.render('error',{
            page:'error'
        });
    }
};
//获取书本信息
exports.getbookInfo=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let bid=fields.bid;
        BookModel.findSortOne({"bid":bid},{"bid":1},function(err,docs){
            if(err){
                res.json({"msg":'失败',"code":0,info:{}});
                return;
            }
            let obj={"bookInfo":docs};
            if(docs==null||docs=={}){
                res.json({"msg":'没有这个页面',"code":2,info:{}});
                return;
            }else{
                AuthorModel.findSortOne({"cid":parseInt(docs['cid'])},{"cid":1},function(err,docs1){
                    if(err){
                        res.json({"msg":'失败',"code":0,info:{}});
                        return;
                    }
                    obj.ainfo=docs1;
                    BookreviewModel.findFnLimit({'bid':docs['bid']},{"startTime":-1},3,function(err,docs2){
                        if(err){
                            res.json({"msg":'失败',"code":0,info:{}});
                            return;
                        }
                        let arrimg=[];
                        let arrnick=[];
                        (function bl(i){
                            i++;
                            if(i==docs2.length){
                                obj.brinfo=docs2;
                                obj.brni={brimg:arrimg,brnick:arrnick};
                                res.json({"msg":'成功',"code":1,info:obj});
                                return;
                            }else{
                                UserinfoModel.findSortOne({"uid":docs2[i]['uid']},{"uid":1},function(err,data1){
                                    //console.log(data1);
                                    arrimg.push(data1['imgurl']);
                                    arrnick.push(data1['nickname']);
                                    bl(i);
                                });
                            }
                        }(-1));
                    });
                })
            }
        });
    });
};
//获取用户信息
exports.getuserHeadimg=function(req,res){
    if(req.session.username){
        UsernameModel.findSortOne({"username":req.session.username},{"uid":1},function(err,docs){
            if(err){
                res.json({"msg":'失败',"code":0,info:{}});
                return;
            }
            UserinfoModel.findSortOne({"uid":docs['uid']},{'uiid':1},function(err,docs1){
                if(err){
                    res.json({"msg":'失败',"code":0,info:{}});
                    return;
                }
                let obj={
                    age:docs['age'],
                    createTime:docs['createTime'],
                    email:docs['email'],
                    sex:docs['sex'],
                    uid:docs['uid'],
                    username:docs['username']
                };
                res.json({"msg":'成功',"code":1,info:{username:obj,userinfo:docs1}});
            });
        });
    }else{
        res.json({"msg":'失败',"code":0,info:{}});
    }
};
//获取粉丝打赏信息
exports.getariaFansNum=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let bid = fields.bid;
        AriafansModel.findFnLimit({"bid":bid},{"reward":-1},3,function(err,docs){
            if(err){
                res.json({"msg":'失败',"code":0,info:{}});
                return;
            }
            //console.log(docs);
            let arrAriaFans=[];
            let arrAriaFansInfo=[];
            (function bl(i){
                i++;
                if(i==docs.length){
                    res.json({"msg":'成功',"code":1,info:{arrAriaFans:arrAriaFans,arrAriaFansInfo:arrAriaFansInfo}});
                    return;
                }else{
                    arrAriaFans.push(docs[i]);
                    UserinfoModel.findSortOne({"uid":docs[i]['uid']},{"uid":1},function(err,data1){
                        arrAriaFansInfo.push(data1);
                        bl(i);
                    });
                }
            }(-1));
        });
    });
};
//获取粉丝打赏数
exports.getariaFansNums=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let bid = fields.bid;
        AriafansModel.findConut({"bid":bid},function(err,docs) {
            if (err) {
                res.json({"msg":'失败',"code":0,count:0});
                return;
            }
            res.json({"msg":'成功',"code":1,count:docs});
        });
    });
};
exports.getBookTicket=function(req,res){

};
//获取粉丝排行榜
exports.getuserTicket=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let bid = fields.bid;
        let uid = fields.uid;
        AriafansModel.findSortOne({"bid":bid,'uid':uid},{'afid':1},function(err,docs) {
            if (err) {
                res.json({"msg":'失败',"code":0,info:{}});
                return;
            }
            res.json({"msg":'成功',"code":1,info:docs});
        });
    });
};
//加入书架
exports.setBookShelf=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let bid = fields.bid;
        BookshelfModel.findFn({},{'bsid':1},function(err,docs) {
            if (err) {
                res.json({"msg":'失败',"code":0,info:{}});
                return;
            }
            if(docs.length==0){
                BookModel.findSortOne({"bid":bid},{"bid":1},function(err,bm1){
                    let bsm=new BookshelfModel({
                        "bsid":1,
                        "uid":req.session.uid,
                        "bookshelf":[
                            {
                                "sjid":1,
                                "sjname":"默认书架",
                                "books":[{
                                    "readTime":new Date().getTime(),
                                    "updateTime":bm1['updateTime'],
                                    "bid":bid
                                }]
                            }
                        ]
                    });
                    bsm.save(function(err){
                        //收藏数加一
                        BookModel.updateFn({bid:bid},{$inc:{recomendCnt:1}},function(err,result){
                            res.json({"msg":'成功',"code":1});
                        });

                    });

                });
            }else{
                BookshelfModel.findSortOne({uid:req.session.uid},{'bsid':1},function(err,docs1) {
                    if(docs1==null||docs1==undefined){
                        BookshelfModel.findSortOne({},{'bsid':-1},function(err,dod) {
                            BookModel.findSortOne({"bid":bid},{"bid":1},function(err,bm1){
                                let bsm=new BookshelfModel({
                                    "bsid":dod.bsid+1,
                                    "uid":req.session.uid,
                                    "bookshelf":[
                                        {
                                            "sjid":1,
                                            "sjname":"默认书架",
                                            "books":[{
                                                "readTime":new Date().getTime(),
                                                "updateTime":bm1['updateTime'],
                                                "bid":bid
                                            }]
                                        }
                                    ]
                                });
                                bsm.save(function(err){
                                    //收藏数加一
                                    BookModel.updateFn({bid:bid},{$inc:{recomendCnt:1}},function(err,result){
                                        res.json({"msg":'成功',"code":1});
                                    });
                                });
                            });
                        })
                    }else{
                        let i1=true;
                        let i2=true;
                        let key=true;
                        for(let i=0;i<docs1['bookshelf'].length;i++){
                            for(let j=0;j<docs1['bookshelf'][i]['books'].length;j++){
                                if(docs1['bookshelf'][i]['books'][j]['bid']==bid){
                                    i1=i;
                                    i2=j;
                                    key=false;
                                    break;
                                }
                            }
                        }
                        if(key==false){
                            res.json({"msg":'已在书架上',"code":2});
                        }else{
                            BookModel.findSortOne({"bid":bid},{"bid":1},function(err,bm1){
                                BookshelfModel.updateFn({"uid":req.session.uid},{$push:{'bookshelf.0.books':{"bid":bid,"readTime":new Date().getTime(),"updateTime":bm1["updateTime"]}}},function(err,docs){
                                    //收藏数加一
                                    BookModel.updateFn({bid:bid},{$inc:{recomendCnt:1}},function(err,result){
                                        res.json({"msg":'成功',"code":1});
                                    });
                                });
                            });
                        }
                    }
                });
            }
        });
    });
};
//获取书架
exports.getBookshelfType=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let bid = fields.bid;
        BookshelfModel.findSortOne({uid:req.session.uid},{'bsid':1},function(err,docs1) {
           if(docs1==""||docs1==null){
                res.json({"msg":'没在书架上',"code":0,info:{}});
            }else{
                let key=true;
                let yuarr={};
                for(let i=0;i<docs1['bookshelf'].length;i++){
                    for(let j=0;j<docs1['bookshelf'][i]['books'].length;j++){
                        if(docs1['bookshelf'][i]['books'][j]['bid']==bid){
                            yuarr.chapter=docs1['bookshelf'][i]['books'][j]['chapter'];
                            yuarr.chapterName=docs1['bookshelf'][i]['books'][j]['chapterName'];
                            key=false;
                            break;
                        }
                    }
                }
                if(key){
                    res.json({"msg":'没在书架上',"code":2,info:{}});
                }else{
                    res.json({"msg":'书架中已存在',"code":1,info:yuarr});
                }
            }
        });
    });
};
//增加点击
exports.getBookClickNum=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
       let bid=parseInt(fields.bid);
       BookModel.updateFn({bid:bid},{$inc:{clickCnt:1}},function(err,doc){
           if(err){
               res.json({code:0,msg:"失败"});
               return;
           }
           res.json({code:1,msg:"成功"});
       })
    });
};